let udp = null;

Page({
  data: {
    ssidList: [],
    selectedIndex: 0,
    password: '',
    connected: false,
    searching: true,
    isPairing: false,
    carIP: '',
    logList: [],
    phoneIP: '',
    deviceInfo: null,
    deviceTable: [],
    uploadImagePath: ''
  },

  // ------------------------- ✅ 页面加载 -------------------------
  onLoad() {
    this.addLog("小程序启动，自动搜索小车中...");
    this.listenUDP();
    setTimeout(() => {
      if (!this.data.connected) {
        this.setData({ searching: false });
        this.addLog("未发现小车，准备进入配网页");
      }
    }, 2000);
  },

  // ------------------------- ✅ 日志记录 -------------------------
  addLog(msg) {
    const list = this.data.logList;
    list.push(`[${new Date().toLocaleTimeString()}] ${msg}`);
    this.setData({ logList: list });
  },

  // ------------------------- ✅ 扫描 WiFi -------------------------
  scanWiFiList() {
    this.addLog("尝试获取WiFi列表...");
    wx.request({
      url: 'http://192.168.4.1/scan',
      method: 'GET',
      success: (res) => {
        if (Array.isArray(res.data)) {
          this.setData({ ssidList: res.data, selectedIndex: 0, isPairing: true });
          this.addLog("WiFi列表获取成功");
        } else {
          this.addLog("WiFi列表格式异常");
        }
      },
      fail: () => {
        this.addLog("无法访问192.168.4.1，请确认连接了热点");
        wx.showModal({ title: '提示', content: '请连接热点 xiaobai_car', showCancel: false });
      }
    });
  },

  onSSIDChange(e) {
    this.setData({ selectedIndex: e.detail.value });
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },

  // ------------------------- ✅ 配网发送 -------------------------
  sendWiFiConfig() {
    const ssid = this.data.ssidList[this.data.selectedIndex];
    const password = this.data.password;
    if (!password) {
      wx.showToast({ title: '请输入密码', icon: 'none' });
      return;
    }
    this.addLog(`发送配网请求：${ssid}`);
    wx.request({
      url: 'http://192.168.4.1/connect',
      method: 'POST',
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      data: { ssid, password },
      success: (res) => {
        if (res.data === 'Connected successfully!') {
          this.setData({ isPairing: false });
          this.addLog("配网成功，请将手机连接回家庭WiFi");
          wx.showModal({
            title: '提示',
            content: '小车已连接家庭WiFi，请将手机也连接相同网络，小程序将自动识别',
            showCancel: false
          });
        } else {
          this.addLog("配网失败，可能密码错误");
        }
      },
      fail: () => {
        this.addLog("配网请求失败");
      }
    });
  },

  // ------------------------- ✅ UDP 广播监听 -------------------------
  listenUDP() {
    this.addLog("监听UDP端口 4210 中...");
    udp = wx.createUDPSocket();
    udp.bind(4210);
    udp.onMessage((res) => {
      const msg = String.fromCharCode.apply(null, new Uint8Array(res.message));
      if (msg.startsWith('connected@')) {
        const ip = msg.split('@')[1];
        if (!this.data.connected) {
          this.setData({ carIP: ip, connected: true, searching: false, isPairing: false });
          this.addLog(`小车上线，IP=${ip}`);
          wx.showToast({ title: '已连接小车', icon: 'success' });
          udp.send({ address: ip, port: 4210, message: '9' });
        }
      }
    });
  },

  // ------------------------- ✅ 控制指令 -------------------------
  sendCommandStart(e) {
    const cmd = e.currentTarget.dataset.cmd;
    if (!this.data.carIP) return;
    udp.send({ address: this.data.carIP, port: 4210, message: cmd });
    this.addLog(`发送控制指令：${cmd}`);
  },

  sendCommandEnd() {
    if (!this.data.carIP) return;
    udp.send({ address: this.data.carIP, port: 4210, message: '0' });
    this.addLog("松开按钮，发送停止指令");
  },

  sendStop() {
    if (!this.data.carIP) return;
    udp.send({ address: this.data.carIP, port: 4210, message: '0' });
    this.addLog("发送停止指令");
  },

  clearWiFi() {
    if (!this.data.carIP) return;
    wx.showModal({
      title: '确认操作',
      content: '确定要清除小车已保存的WiFi吗？小车将恢复为热点模式',
      success: (res) => {
        if (res.confirm) {
          udp.send({ address: this.data.carIP, port: 4210, message: '8' });
          this.addLog("已发送清除WiFi指令");
          wx.showToast({ title: '已发送清除指令', icon: 'none' });
        }
      }
    });
  },

  sendSingleCommand(e) {
    const cmd = e.currentTarget.dataset.cmd;
    if (!this.data.carIP) return;
    if (!this.data.carIP) return;
    udp.send({ address: this.data.carIP, port: 4210, message: cmd });
    this.addLog(`发送瞬时指令：${cmd}`);
  },

  // ------------------------- ✅ 设备信息处理 -------------------------
  buildDeviceTable(info) {
    return [
      { label: '设备名称', value: info.device_name || '-' },
      { label: '设备ID', value: info.device_id || '-' },
      { label: '固件版本', value: info.firmware_ver || '-' },
      { label: '硬件版本', value: info.hardware_rev || '-' },
      { label: '触摸授权', value: info.touch_authorized ? '已授权' : '未授权' },
      { label: '授权到期', value: info.touch_expire_at || '无' },
      { label: 'WiFi信号强度', value: (info.signal_strength ?? 'N/A') + ' dBm' },
      { label: '当前连接', value: info.connect_type || '-' },
      { label: '设备IP', value: info.device_ip || '-' },
      { label: '运行时长', value: (info.uptime_ms || 0) + ' ms' }
    ];
  },

  logDeviceInfo(info) {
    const lines = [
      `设备名称: ${info.device_name || '-'}`,
      `设备ID: ${info.device_id || '-'}`,
      `固件版本: ${info.firmware_ver || '-'}`,
      `硬件版本: ${info.hardware_rev || '-'}`,
      `触摸授权: ${info.touch_authorized ? '已授权' : '未授权'}`,
      `授权到期: ${info.touch_expire_at || '无'}`,
      `连接方式: ${info.connect_type || '-'}`,
      `设备IP: ${info.device_ip || '-'}`,
      `信号强度: ${(info.signal_strength ?? 'N/A')} dBm`,
      `运行时长: ${(info.uptime_ms || 0)} ms`
    ];
    lines.forEach(l => this.addLog(l));
  },

  onPhoneIPInput(e) {
    this.setData({ phoneIP: e.detail.value });
  },

  sendPhoneIP() {
    const { phoneIP, carIP } = this.data;
    if (!phoneIP) {
      wx.showToast({ title: '请输入手机IP', icon: 'none' });
      return;
    }
    this.addLog(`下发手机IP至设备：${phoneIP}`);
    const ip = carIP || '192.168.1.100';
    wx.request({
      url: `http://${ip}/device/info`,
      method: 'GET',
      success: (res) => {
        const info = (typeof res.data === 'string') ? JSON.parse(res.data) : res.data;
        this.addLog("收到设备信息，开始解析...");
        this.logDeviceInfo(info);
        const deviceTable = this.buildDeviceTable(info);
        this.setData({ deviceInfo: info, deviceTable });
        this.fakeServerRegister(info);
      },
      fail: () => {
        this.addLog("访问设备失败，请检查IP或连接状态");
      }
    });
  },

  fakeServerRegister(deviceInfo) {
    this.addLog("模拟服务器注册中...");
    setTimeout(() => {
      const token = "FAKE-" + Math.random().toString(36).substring(2, 8).toUpperCase();
      this.addLog("服务器注册成功，Token=" + token);
      this.setData({ fakeToken: token });
    }, 800);
  },

// ------------------------- ✅ 图片选择与裁剪 -------------------------
chooseImage() {
  wx.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    success: (res) => {
      const path = res.tempFilePaths[0];
      console.log('[Index] 选择的图片路径:', path);
      this.setData({ uploadImagePath: path });
      wx.setStorageSync('tempCropPath', path);
      wx.navigateTo({
        url: '/pages/index/crop/crop',
        success: (res) => {
          res.eventChannel.on('cropDone', (data) => {
            console.log('[Index] 裁剪完成，接收到路径:', data.path);
            this.setData({ uploadImagePath: data.path });
            wx.setStorageSync('tempCropPath', data.path);
          });
        }
      });
    },
    fail: () => wx.showToast({ title: '未选择图片', icon: 'none' })
  });
},

editImage() {
  const path = this.data.uploadImagePath || wx.getStorageSync('tempCropPath');
  if (!path) {
    wx.showToast({ title: '请先选择图片', icon: 'none' });
    return;
  }
  wx.setStorageSync('tempCropPath', path);
  wx.navigateTo({
    url: '/pages/index/crop/crop',
    success: (res) => {
      res.eventChannel.on('cropDone', (data) => {
        console.log('[Index] 裁剪完成，接收到路径:', data.path);
        this.setData({ uploadImagePath: data.path });
        wx.setStorageSync('tempCropPath', data.path);
      });
    }
  });
},

// ------------------------- ✅ 图片压缩与上传 -------------------------
// ------------------------- ✅ 压缩并上传图片（带详细日志） -------------------------
compressAndUpload() {
  const _this = this;
  const path = this.data.uploadImagePath;

  if (!path) {
    wx.showToast({ title: '请先选择并裁剪图片', icon: 'none' });
    _this.addLog('⚠️ 未选择图片，压缩终止');
    return;
  }

  _this.addLog('🌀 [压缩流程] 开始获取图片信息...');
  wx.getImageInfo({
    src: path,
    success(info) {
      const { width, height } = info;
      const size = 240;
      const scale = Math.min(width, height) / size;
      const sx = (width - size * scale) / 2;
      const sy = (height - size * scale) / 2;

      _this.addLog(`📐 图片原始尺寸：${width}x${height}，裁剪中心区域`);
      _this.addLog('🖼️ 绘制到隐藏 canvas 中...');
      const ctx = wx.createCanvasContext('cropCanvas', _this);
      ctx.drawImage(path, sx, sy, size * scale, size * scale, 0, 0, size, size);

      ctx.draw(false, () => {
        _this.addLog('🔄 Canvas绘制完成，开始导出 JPG...');

        wx.canvasToTempFilePath({
          canvasId: 'cropCanvas',
          destWidth: size,
          destHeight: size,
          fileType: 'jpg',
          quality: 0.35,
          success: (res) => {
            const finalPath = res.tempFilePath;

            const fs = wx.getFileSystemManager();
            fs.stat({
              path: finalPath,
              success(statRes) {
                const kb = (statRes.size / 1024).toFixed(1);
                _this.addLog(`✅ 压缩成功，输出尺寸 240x240，大小约 ${kb}KB`);
              },
              fail() {
                _this.addLog('⚠️ 无法读取压缩后文件大小');
              }
            });

            _this.setData({ uploadImagePath: finalPath });
            _this.addLog('📤 准备上传...');
            _this._uploadWithProgress(finalPath);
          },
          fail: (err) => {
            wx.showToast({ title: '压缩失败', icon: 'none' });
            _this.addLog('❌ 压缩失败：' + err.errMsg);
          }
        });
      });
    },
    fail: () => {
      wx.showToast({ title: '图片信息获取失败', icon: 'none' });
      _this.addLog('❌ 获取图片信息失败');
    }
  });
}
,

_uploadWithProgress(filePath) {
  const carIP = this.data.carIP;
  if (!carIP) {
    wx.showToast({ title: '未连接设备', icon: 'none' });
    this.addLog('❌ 上传失败：未获取到小车 IP');
    return;
  }

  this.addLog('🚀 正在上传至小车...');
  wx.showLoading({ title: '上传中 0%', mask: true });

  const uploadTask = wx.uploadFile({
    url: `http://${carIP}/upload`,
    filePath: filePath,
    name: 'file',
    success: (res) => {
      wx.hideLoading();
      if (res.statusCode === 200) {
        wx.showToast({ title: '上传成功', icon: 'success' });
        this.addLog(`✅ 上传成功，设备返回：${res.data}`);
      } else {
        wx.showToast({ title: '上传失败', icon: 'none' });
        this.addLog(`❌ 上传失败，状态码：${res.statusCode}`);
      }
    },
    fail: (err) => {
      wx.hideLoading();
      wx.showToast({ title: '上传异常', icon: 'none' });
      this.addLog(`❌ 上传异常：${err.errMsg}`);
    }
  });

  uploadTask.onProgressUpdate((res) => {
    wx.showLoading({ title: `上传中 ${res.progress}%`, mask: true });
    if (res.progress % 10 === 0) {
      this.addLog(`📶 上传进度：${res.progress}%`);
    }
  });
},

// ✅ Page 结束
});
